package com.xinxin.facelinker.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.easemob.chatuidemo.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.xinxin.facelinker.Config;
import com.xinxin.facelinker.adapter.MotionImageAdapter;
import com.xinxin.facelinker.widget.WrapHeightGridView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class AddMyMotionActivity extends Activity {

    private EditText etAddMyMotion;
    private WrapHeightGridView gvMotionImage;
    private ImageView composePicture;
    private ImageView composeEmotion;
    private ImageView composeSend;
    private String my_account_num;
    private View btnBack;
    private static int CAMERA_REQUEST_CODE = 1;
    private static int GALLERY_REQUEST_CODE = 2;
    private String[] array=new String[]{"摄像头", "图库"};
    private String ImageName=null;
    final int LIST_DIALOG=1;
    private int selectNum=0;
    private ArrayList<Uri> motionPictureList=new ArrayList<Uri>();
    private MotionImageAdapter adapter;

    HttpUtils httpUtils = new HttpUtils();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_my_motion);

        etAddMyMotion= (EditText) findViewById(R.id.etAddMyMotion);
        gvMotionImage= (WrapHeightGridView) findViewById(R.id.gvMotionImage);
        composePicture= (ImageView) findViewById(R.id.composePicture);
        composeEmotion= (ImageView) findViewById(R.id.composeEmotion);
        composeSend= (ImageView) findViewById(R.id.composeSend);
        my_account_num=getIntent().getStringExtra(Config.KEY_MY_ACCOUNT_NUM);
        btnBack=findViewById(R.id.btnBack);
        adapter=new MotionImageAdapter(AddMyMotionActivity.this,motionPictureList,gvMotionImage);
        gvMotionImage.setAdapter(adapter);

        composePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter.getCount()<= 9) {
                    showDialog(LIST_DIALOG);
                }
            }
        });

        gvMotionImage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position==adapter.getCount()-1){
                    if(adapter.getCount()<=9) {
                        showDialog(LIST_DIALOG);
                    }
                }
            }
        });

        composeSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(etAddMyMotion.getText().toString().isEmpty()==true){
                    Toast.makeText(AddMyMotionActivity.this, R.string.add_my_motion_can_not_be_empty,Toast.LENGTH_SHORT).show();
                    return;
                }

                final ProgressDialog pd = ProgressDialog.show(AddMyMotionActivity.this, getResources().getString(R.string.add_my_motion_connecting), getResources().getString(R.string.add_my_motion_connecting_to_server));
                RequestParams params = new RequestParams();
                params.addBodyParameter(Config.ACTION, Config.ACTION_ADD_MY_MOTION);
                params.addBodyParameter(Config.KEY_MY_ACCOUNT_NUM, my_account_num);
                params.addBodyParameter(Config.KEY_MY_MOTION, etAddMyMotion.getText().toString());
                httpUtils.send(HttpRequest.HttpMethod.POST, Config.CATEGORIES_URL, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        pd.dismiss();
                        Toast.makeText(AddMyMotionActivity.this, R.string.add_my_motion_success,Toast.LENGTH_SHORT).show();
                        Intent intent=new Intent(AddMyMotionActivity.this,ShowMyMotionActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        pd.dismiss();
                        Toast.makeText(AddMyMotionActivity.this, R.string.add_my_motion_fail,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    //转变uri为file类型
    private Uri convertUri(Uri uri){
        InputStream is=null;
        try {
            is=getContentResolver().openInputStream(uri);
            Bitmap bitmap= BitmapFactory.decodeStream(is);
            is.close();
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //将Bitmap转变为file类型Uri
    private Uri saveBitmap(Bitmap bitmap){
        File tmpDir=new File(Environment.getExternalStorageDirectory()+"/com.xinxin.faceliner");
        if(!tmpDir.exists()) {
            tmpDir.mkdir();
        }
        File img=new File(tmpDir.getAbsolutePath()+"userpicture.png");
        try {
            FileOutputStream fos=new FileOutputStream(img);
            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (data == null) {
                File picture = new File(Environment.getExternalStorageDirectory()+
                        File.separator+ImageName);
                Uri uri = Uri.fromFile(picture);

                motionPictureList.add(uri);
                updateImgs();

                return;

            } else {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap bm = extras.getParcelable("data");
                    Uri uri=saveBitmap(bm);

                    motionPictureList.add(uri);
                    updateImgs();

                    //向数据库中保存图片地址
                    //startImageZoom(uri);
                }
            }
        }else if(requestCode==GALLERY_REQUEST_CODE){

            if(data==null)
                return;
            else {
                Uri uri;
                uri = data.getData();
                Uri fileUri = convertUri(uri);

                motionPictureList.add(fileUri);
                updateImgs();

                //向数据库中保存图片地址
            }
        }
    }

    private void updateImgs() {
        if(motionPictureList.size()>0){
            gvMotionImage.setVisibility(View.VISIBLE);
            adapter.notifyDataSetChanged();
        }else{
            gvMotionImage.setVisibility(View.GONE);
        }
    }

    protected Dialog onCreateDialog(int id) {
        AlertDialog dialog=null;
        switch (id) {
            case LIST_DIALOG:
                AlertDialog.Builder b = new AlertDialog.Builder(this);
                b.setTitle(R.string.select_uploda_picture_method);
                b.setSingleChoiceItems(array, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        selectNum=i;
                    }
                });
                b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (array[selectNum].equals("摄像头")) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            ImageName = System.currentTimeMillis()+".jpg";
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                                    Environment.getExternalStorageDirectory()
                                    , ImageName)));
                            startActivityForResult(intent, CAMERA_REQUEST_CODE);

                        } else {
                            Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("image/*");
                            startActivityForResult(intent, GALLERY_REQUEST_CODE);
                        }
                    }
                });
                dialog = b.create();
                break;
        }
        return dialog;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode== KeyEvent.KEYCODE_BACK){
            finish();
        }

        return true;
    }
}
